import React, { useState, useRef, useEffect } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity, Dimensions, Animated, StatusBar, ActivityIndicator } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Icon from 'react-native-vector-icons/Ionicons';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { foodCultureAPI } from '../api';
import { COLORS, SHADOWS } from '../styles/constants';

const { width, height } = Dimensions.get('window');

/**
 * 美食文创详情页面
 * 展示美食或文创的详细信息，包括图片、标题、描述和音频播放功能
 */
export default function FoodCultureDetailScreen({ route }) {
  const { item: initialItem } = route.params;
  const navigation = useNavigation();
  const insets = useSafeAreaInsets();
  const [item, setItem] = useState(initialItem); // 存储详情数据
  const [loading, setLoading] = useState(false);
  const scrollY = useRef(new Animated.Value(0)).current;
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const scaleAnim = useRef(new Animated.Value(0.95)).current;

  // 头部透明度动画
  const headerOpacity = scrollY.interpolate({
    inputRange: [0, 150],
    outputRange: [0, 1],
    extrapolate: 'clamp',
  });

  // 图片缩放动画
  const imageScale = scrollY.interpolate({
    inputRange: [-100, 0],
    outputRange: [1.3, 1],
    extrapolate: 'clamp',
  });

  // 进入动画
  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
      }),
      Animated.spring(scaleAnim, {
        toValue: 1,
        friction: 8,
        tension: 40,
        useNativeDriver: true,
      }),
    ]).start();
  }, [fadeAnim, scaleAnim]);

  // 加载详情数据
  useEffect(() => {
    loadDetailData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const loadDetailData = async () => {
    if (!initialItem?.id) {
      return;
    }

    try {
      setLoading(true);

      const response = await foodCultureAPI.getFoodCultureDetailById(initialItem.id);

      // 提取数据
      const detailData = response?.data?.data || response?.data || null;

      if (detailData) {

        // 映射字段
        const mappedData = {
          id: detailData.id,
          name: detailData.title || detailData.name,
          image: detailData.image || detailData.coverImage,
          content: detailData.content,
          tag: detailData.tag,
          city: detailData.city,
          type: detailData.tag === 1 ? 'food' : 'culture',
          raw: detailData
        };

        setItem(mappedData);
      } else {
        // 使用列表传过来的数据
        setItem(initialItem);
      }
    } catch (error) {
      // 失败时使用初始数据
      setItem(initialItem);
    } finally {
      setLoading(false);
    }
  };

  // 加载状态
  if (loading && !item) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#FF6B6B" />
        <Text style={styles.loadingText}>加载中...</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" translucent backgroundColor="transparent" />

      {/* 滚动内容 */}
      <Animated.ScrollView
        style={styles.scrollView}
        showsVerticalScrollIndicator={false}
        scrollEventThrottle={16}
        onScroll={Animated.event(
          [{ nativeEvent: { contentOffset: { y: scrollY } } }],
          { useNativeDriver: false } // 改为 false，因为我们需要动画颜色属性
        )}
      >
        {/* 顶部图片 */}
        <Animated.View style={[styles.imageContainer, { transform: [{ scale: imageScale }] }]}>
          <Image
            source={{ uri: item.image || 'https://via.placeholder.com/400x300' }}
            style={styles.mainImage}
            resizeMode="cover"
          />
          {/* 多层渐变遮罩 */}
          <View style={styles.gradientOverlay}>
            <View style={styles.gradientTop} />
            <View style={styles.gradientBottom} />
          </View>
        </Animated.View>

        {/* 内容区域 */}
        <Animated.View
          style={[
            styles.contentContainer,
            {
              opacity: fadeAnim,
              transform: [{ scale: scaleAnim }]
            }
          ]}
        >
          {/* 顶部标签和标题区域 */}
          <View style={styles.headerSection}>
            {/* 类型标签 */}
            <View style={[
              styles.typeTag,
              { backgroundColor: item.type === 'food' ? '#FFF5F5' : '#F0F7FF' }
            ]}>
              <View style={[
                styles.typeIconWrapper,
                { backgroundColor: item.type === 'food' ? '#FF6B6B' : '#4A90E2' }
              ]}>
                <MaterialCommunityIcons
                  name={item.type === 'food' ? 'food' : 'palette'}
                  size={14}
                  color="#fff"
                />
              </View>
              <Text style={[
                styles.typeText,
                { color: item.type === 'food' ? '#FF6B6B' : '#4A90E2' }
              ]}>
                {item.type === 'food' ? '特色美食' : '文化创意'}
              </Text>
            </View>

            {/* 标题 */}
            <Text style={styles.title}>{item.name}</Text>

            {/* 装饰线 */}
            <View style={styles.titleDecoration}>
              <View style={styles.decorationDot} />
              <View style={styles.decorationLine} />
              <View style={styles.decorationDot} />
            </View>
          </View>

          {/* 音频播放控制 */}
          {item.raw?.voiceUrl && (
            <View style={styles.audioInfoBanner}>
              <Icon name="information-circle-outline" size={20} color="#fff" style={styles.audioInfoIcon} />
              <Text style={styles.audioInfoText}>语音讲解功能已下线</Text>
            </View>
          )}

          {/* 详细描述 */}
          <View style={styles.descriptionSection}>
            <View style={styles.sectionTitleWrapper}>
              <View style={styles.sectionIconWrapper}>
                <Icon name="document-text" size={18} color="#FF6B6B" />
              </View>
              <Text style={styles.sectionTitle}>详细介绍</Text>
            </View>

            <View style={styles.descriptionCard}>
              <Text style={styles.description}>
                {item.content || '暂无详细介绍'}
              </Text>
            </View>
          </View>

          {/* 底部留白 */}
          {item.raw?.voiceUrl && (
            <View style={styles.audioInfoCard}>
              <Icon name="volume-mute" size={36} color="#FF6B6B" style={styles.audioInfoCardIcon} />
              <Text style={styles.audioInfoCardTitle}>语音介绍暂不可用</Text>
              <Text style={styles.audioInfoCardDesc}>我们正在升级语音服务，当前请通过文字内容了解详情。</Text>
            </View>
          )}
          <View style={{ height: 50 }} />
        </Animated.View>
      </Animated.ScrollView>

      {/* 顶部导航栏 */}
      <Animated.View
        style={[
          styles.header,
          {
            paddingTop: insets.top,
            backgroundColor: headerOpacity.interpolate({
              inputRange: [0, 1],
              outputRange: ['rgba(0,0,0,0)', 'rgba(255,255,255,0.95)']
            })
          }
        ]}
      >
        <Animated.View
          style={[
            styles.backButton,
            {
              backgroundColor: headerOpacity.interpolate({
                inputRange: [0, 1],
                outputRange: ['rgba(0,0,0,0.4)', 'rgba(255,107,107,0.1)']
              })
            }
          ]}
        >
          <TouchableOpacity
            style={styles.buttonTouchable}
            onPress={() => navigation.goBack()}
            activeOpacity={0.8}
          >
            <Icon
              name="arrow-back"
              size={24}
              color="#fff"
              style={styles.iconStyle}
            />
          </TouchableOpacity>
        </Animated.View>

        <Animated.View style={{ flex: 1, opacity: headerOpacity }}>
          <Text style={styles.headerTitle} numberOfLines={1}>
            {item.name}
          </Text>
        </Animated.View>
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background.secondary,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: COLORS.background.card,
  },
  loadingText: {
    marginTop: 12,
    fontSize: 16,
    color: COLORS.text.secondary,
  },
  scrollView: {
    flex: 1,
  },
  imageContainer: {
    width,
    height: height * 0.45,
    overflow: 'hidden',
  },
  mainImage: {
    width: '100%',
    height: '100%',
  },
  gradientOverlay: {
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'space-between',
  },
  gradientTop: {
    height: 120,
    backgroundColor: 'rgba(0,0,0,0.35)',
  },
  gradientBottom: {
    height: 160,
    backgroundColor: 'rgba(0,0,0,0.45)',
  },
  contentContainer: {
    marginTop: -60,
    padding: 24,
    paddingTop: 30,
    backgroundColor: COLORS.background.card,
    borderTopLeftRadius: 24,
    borderTopRightRadius: 24,
    minHeight: height * 0.6,
  },
  headerSection: {
    marginBottom: 24,
  },
  typeTag: {
    alignSelf: 'flex-start',
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 20,
    marginBottom: 12,
  },
  typeIconWrapper: {
    width: 24,
    height: 24,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 8,
  },
  typeText: {
    fontSize: 14,
    fontWeight: '600',
  },
  title: {
    fontSize: 28,
    fontWeight: '700',
    color: COLORS.text.primary,
    marginBottom: 12,
    lineHeight: 34,
  },
  titleDecoration: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  decorationDot: {
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: COLORS.primary,
  },
  decorationLine: {
    flex: 1,
    height: 2,
    backgroundColor: `${COLORS.primary}4D`,
    marginHorizontal: 6,
  },
  descriptionSection: {
    marginBottom: 24,
  },
  sectionTitleWrapper: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  sectionIconWrapper: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: COLORS.primaryLight,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: COLORS.text.primary,
  },
  descriptionCard: {
    padding: 18,
    backgroundColor: COLORS.background.secondary,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: COLORS.border.light,
  },
  description: {
    fontSize: 16,
    color: COLORS.text.secondary,
    lineHeight: 24,
  },
  header: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: 56,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    zIndex: 10,
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0,
        shadowRadius: 4,
      },
    }),
  },
  backButton: {
    width: 42,
    height: 42,
    borderRadius: 21,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
    overflow: 'hidden',
  },
  buttonTouchable: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  iconStyle: {
    // 占位样式，确保图标正确显示
  },
  headerTitle: {
    fontSize: 17,
    fontWeight: '700',
    color: COLORS.text.primary,
  },
  audioInfoBanner: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: COLORS.primary,
    paddingHorizontal: 14,
    paddingVertical: 10,
    borderRadius: 12,
    marginBottom: 20,
  },
  audioInfoIcon: {
    marginRight: 8,
  },
  audioInfoText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '500',
  },
  audioInfoCard: {
    marginTop: 12,
    padding: 20,
    borderRadius: 18,
    backgroundColor: COLORS.primaryLight,
    borderWidth: 1,
    borderColor: COLORS.primarySoft,
    alignItems: 'center',
  },
  audioInfoCardIcon: {
    marginBottom: 12,
  },
  audioInfoCardTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: COLORS.error,
    marginBottom: 8,
  },
  audioInfoCardDesc: {
    fontSize: 15,
    color: COLORS.text.tertiary,
    textAlign: 'center',
    lineHeight: 22,
  },
});

